import React, { useContext, useState, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Alert,
  TextInput,
  Keyboard,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import TestQuesCard from "../../components/preAdmin/TestQuesCard";
import TestContext from "../../context/preparation/TestContext";
import LoadingBar from "../../components/InterView/LoadingBar";

const TestPreview = ({ navigation, route }) => {
  const { editTest, isTestLoading } = useContext(TestContext);
  const { test, type } = route.params;
  const [isEdit, setIsEdit] = useState(false);
  const [title, setTitle] = useState(test.title);
  const [deletedId, setDeletedId] = useState(null);
  const [questions, setQuestions] = useState(test.questions);

  const [keyboardIsOpen, setKeyboardIsOpen] = useState(false);

  React.useLayoutEffect(() => {
    if (type !== "readOnly") {
      navigation.setOptions({
        headerRight: () => (
          <TouchableOpacity
            onPress={() => {
              setIsEdit((pre) => setIsEdit(!pre));
            }}
          >
            <AntDesign name="edit" size={22} color="#fff" />
          </TouchableOpacity>
        ),
      });
    }
  }, [navigation]);

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeAllListeners("keyboardDidShow");
      Keyboard.removeAllListeners("keyboardDidHide");
    };
  }, []);

  const _keyboardDidShow = () => {
    setKeyboardIsOpen(true);
  };

  const _keyboardDidHide = () => {
    setKeyboardIsOpen(false);
  };

  const deleteQuestionById = (id) => {
    Alert.alert("提示", "确定删除该题目吗?", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: () => {
          const newQueations = questions.filter((item) => item._id !== id);
          setQuestions(newQueations);
          Alert.alert("", "删除成功", [
            {
              text: "确定",
            },
          ]);
        },
      },
    ]);
  };

  const editQuestion = (ques) => {
    const newQuestions = questions.map((item) => {
      return item._id === ques._id ? ques : item;
    });
    setQuestions(newQuestions);
  };

  const onConfirm = () => {
    let now = new Date();
    let mytime =
      now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    Alert.alert("提示", "确定保存此次修改吗?", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: () => {
          test.questions = questions;
          test.time = mytime;
          test.title = title;
          editTest(test, () => navigation.navigate("TestManage"));
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isTestLoading} />
      <FlatList
        data={questions}
        ListHeaderComponent={
          isEdit && (
            <View style={styles.top}>
              <View style={styles.title}>
                <Text style={styles.titleIcon}>* </Text>
                <Text style={styles.titleText}>标题</Text>
              </View>
              <TextInput
                style={styles.inputBox}
                multiline={true}
                value={title}
                placeholder="请输入试卷标题"
                onChangeText={(text) => {
                  setTitle(text);
                }}
              />
            </View>
          )
        }
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <TestQuesCard
            index={index}
            item={item}
            isEdit={isEdit}
            onEdit={() => {
              navigation.navigate("EditTestQues", {
                testQues: item,
                variety: "test",
                confirmEdit: editQuestion,
              });
            }}
            isDelete={isEdit}
            deletedId={deletedId}
            onDeleted={deleteQuestionById}
            isAdd={false}
          />
        )}
      />
      {isEdit && !keyboardIsOpen && (
        <View style={styles.buttonGroup}>
          <TouchableOpacity
            style={styles.addbutton}
            onPress={() =>
              navigation.navigate("AddQuesInTest", {
                originQues: questions,
                setQuestions: setQuestions,
              })
            }
          >
            <Text style={styles.addText}>增加题目</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.button} onPress={onConfirm}>
            <Text style={styles.text}>保存</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    backgroundColor: "#f5f5f5",
    flex: 1,
  },
  buttonGroup: {
    flexDirection: "row",
    justifyContent: "space-around",
    padding: 5,
  },
  button: {
    flex: 3,
    borderRadius: 5,
    margin: 10,
    padding: 10,
    backgroundColor: "#3ABEF0",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  text: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
  addbutton: {
    flex: 2,
    borderRadius: 5,
    margin: 10,
    padding: 10,
    borderColor: "#3ABEF0",
    borderWidth: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  addText: {
    fontSize: 16,
    color: "#3ABEF0",
    fontWeight: "bold",
  },
  top: {
    margin: 13,
    marginBottom: 5,
    backgroundColor: "#fff",
    padding: 10,
  },
  title: {
    flexDirection: "row",
    marginBottom: 10,
  },
  titleIcon: { color: "red", fontSize: 16 },
  titleText: { color: "#555", fontSize: 16 },
  inputBox: {
    borderColor: "#ddd",
    borderWidth: 1,

    borderRadius: 2,
    padding: 10,
  },
});

export default TestPreview;
